package org.dxy.trigger.http.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.request.workshop.CreateWorkshopRequest;
import org.dxy.api.dto.request.workshop.UpdateWorkshopRequest;
import org.dxy.api.response.R;
import org.dxy.infrastructure.entity.query.FactoryViewEntity;
import org.dxy.infrastructure.entity.query.WorkshopViewEntity;
import org.dxy.infrastructure.persistent.service.FactoryViewService;
import org.dxy.infrastructure.persistent.service.WorkshopViewService;
import org.dxy.infrastructure.util.UserContext;
import org.dxy.trigger.http.service.WorkshopApplicationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车间应用服务实现类
 * @author dxy
 * @createTime 2025/8/18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkshopApplicationServiceImpl implements WorkshopApplicationService {
    
    private final WorkshopViewService workshopViewService;
    private final FactoryViewService factoryViewService;

    @Transactional
    @Override
    public R<Long> create(CreateWorkshopRequest request) {
        try {
            log.info("开始创建车间: workshopCode={}, workshopName={}, factoryId={}", 
                    request.getWorkshopCode(), request.getWorkshopName(), request.getFactoryId());
            
            // 检查工厂是否存在
            FactoryViewEntity factory = factoryViewService.getById(request.getFactoryId());
            if (factory == null) {
                return R.fail("所属工厂不存在");
            }
            
            // 检查车间编码是否已存在
            if (workshopViewService.existsByWorkshopCode(request.getWorkshopCode())) {
                return R.fail("车间编码已存在");
            }
            
            // 创建车间实体
            WorkshopViewEntity workshop = WorkshopViewEntity.builder()
                    .workshopCode(request.getWorkshopCode())
                    .workshopName(request.getWorkshopName())
                    .factoryId(request.getFactoryId())
                    .factoryName(factory.getFactoryName())
                    .workshopType(request.getWorkshopType())
                    .area(request.getArea())
                    .manager(request.getManager())
                    .phone(request.getPhone())
                    .status("ACTIVE")
                    .description(request.getDescription())
                    .createdBy(UserContext.getCurrentUser())
                    .createdTime(LocalDateTime.now())
                    .updatedBy(UserContext.getCurrentUser())
                    .updatedTime(LocalDateTime.now())
                    .deleted(0)
                    .build();
            
            workshopViewService.save(workshop);
            
            log.info("车间创建成功: workshopId={}", workshop.getId());
            return R.ok(workshop.getId(), "车间创建成功");
            
        } catch (Exception e) {
            log.error("创建车间失败", e);
            return R.fail("创建车间失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> update(Long workshopId, UpdateWorkshopRequest request) {
        try {
            log.info("开始更新车间: workshopId={}", workshopId);
            
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop == null) {
                return R.fail("车间不存在");
            }
            
            // 检查工厂是否存在
            FactoryViewEntity factory = factoryViewService.getById(request.getFactoryId());
            if (factory == null) {
                return R.fail("所属工厂不存在");
            }
            
            // 更新车间信息
            workshop.setWorkshopName(request.getWorkshopName());
            workshop.setFactoryId(request.getFactoryId());
            workshop.setFactoryName(factory.getFactoryName());
            workshop.setWorkshopType(request.getWorkshopType());
            workshop.setArea(request.getArea());
            workshop.setManager(request.getManager());
            workshop.setPhone(request.getPhone());
            workshop.setDescription(request.getDescription());
            workshop.setUpdatedBy(UserContext.getCurrentUser());
            workshop.setUpdatedTime(LocalDateTime.now());
            
            workshopViewService.updateById(workshop);
            
            log.info("车间更新成功: workshopId={}", workshopId);
            return R.ok("车间更新成功");
            
        } catch (Exception e) {
            log.error("更新车间失败, workshopId={}", workshopId, e);
            return R.fail("更新车间失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> enable(Long workshopId) {
        try {
            log.info("开始启用车间: workshopId={}", workshopId);
            
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop == null) {
                return R.fail("车间不存在");
            }
            
            if ("ACTIVE".equals(workshop.getStatus())) {
                return R.fail("车间已经是启用状态");
            }
            
            workshop.setStatus("ACTIVE");
            workshop.setUpdatedBy(UserContext.getCurrentUser());
            workshop.setUpdatedTime(LocalDateTime.now());
            
            workshopViewService.updateById(workshop);
            
            log.info("车间启用成功: workshopId={}", workshopId);
            return R.ok("车间启用成功");
            
        } catch (Exception e) {
            log.error("启用车间失败, workshopId={}", workshopId, e);
            return R.fail("启用车间失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> disable(Long workshopId) {
        try {
            log.info("开始禁用车间: workshopId={}", workshopId);
            
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop == null) {
                return R.fail("车间不存在");
            }
            
            if ("INACTIVE".equals(workshop.getStatus())) {
                return R.fail("车间已经是禁用状态");
            }
            
            workshop.setStatus("INACTIVE");
            workshop.setUpdatedBy(UserContext.getCurrentUser());
            workshop.setUpdatedTime(LocalDateTime.now());
            
            workshopViewService.updateById(workshop);
            
            log.info("车间禁用成功: workshopId={}", workshopId);
            return R.ok("车间禁用成功");
            
        } catch (Exception e) {
            log.error("禁用车间失败, workshopId={}", workshopId, e);
            return R.fail("禁用车间失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> setMaintenance(Long workshopId) {
        try {
            log.info("开始设置车间维护状态: workshopId={}", workshopId);
            
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop == null) {
                return R.fail("车间不存在");
            }
            
            if ("MAINTENANCE".equals(workshop.getStatus())) {
                return R.fail("车间已经是维护状态");
            }
            
            workshop.setStatus("MAINTENANCE");
            workshop.setUpdatedBy(UserContext.getCurrentUser());
            workshop.setUpdatedTime(LocalDateTime.now());
            
            workshopViewService.updateById(workshop);
            
            log.info("车间设置维护状态成功: workshopId={}", workshopId);
            return R.ok("车间设置维护状态成功");
            
        } catch (Exception e) {
            log.error("设置车间维护状态失败, workshopId={}", workshopId, e);
            return R.fail("设置车间维护状态失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> delete(Long workshopId) {
        try {
            log.info("开始删除车间: workshopId={}", workshopId);
            
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop == null) {
                return R.fail("车间不存在");
            }
            
            // TODO: 检查是否有关联的产线或工位
            
            workshopViewService.removeById(workshopId);
            
            log.info("车间删除成功: workshopId={}", workshopId);
            return R.ok("车间删除成功");
            
        } catch (Exception e) {
            log.error("删除车间失败, workshopId={}", workshopId, e);
            return R.fail("删除车间失败: " + e.getMessage());
        }
    }

    @Override
    public R<Page<WorkshopViewEntity>> list(Page<WorkshopViewEntity> page, WorkshopViewEntity query) {
        try {
            LambdaQueryWrapper<WorkshopViewEntity> queryWrapper = new LambdaQueryWrapper<>();
            
            if (query != null) {
                if (query.getWorkshopCode() != null && !query.getWorkshopCode().isEmpty()) {
                    queryWrapper.like(WorkshopViewEntity::getWorkshopCode, query.getWorkshopCode());
                }
                if (query.getWorkshopName() != null && !query.getWorkshopName().isEmpty()) {
                    queryWrapper.like(WorkshopViewEntity::getWorkshopName, query.getWorkshopName());
                }
                if (query.getFactoryId() != null) {
                    queryWrapper.eq(WorkshopViewEntity::getFactoryId, query.getFactoryId());
                }
                if (query.getWorkshopType() != null && !query.getWorkshopType().isEmpty()) {
                    queryWrapper.eq(WorkshopViewEntity::getWorkshopType, query.getWorkshopType());
                }
                if (query.getStatus() != null && !query.getStatus().isEmpty()) {
                    queryWrapper.eq(WorkshopViewEntity::getStatus, query.getStatus());
                }
                if (query.getManager() != null && !query.getManager().isEmpty()) {
                    queryWrapper.like(WorkshopViewEntity::getManager, query.getManager());
                }
            }
            
            queryWrapper.orderByDesc(WorkshopViewEntity::getCreatedTime);
            
            Page<WorkshopViewEntity> result = workshopViewService.page(page, queryWrapper);
            return R.ok(result, "查询成功");
            
        } catch (Exception e) {
            log.error("查询车间列表失败", e);
            return R.fail("查询车间列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<WorkshopViewEntity> getById(Long workshopId) {
        try {
            WorkshopViewEntity workshop = workshopViewService.getById(workshopId);
            if (workshop != null) {
                return R.ok(workshop, "查询成功");
            } else {
                return R.fail("车间不存在");
            }
        } catch (Exception e) {
            log.error("查询车间详情失败, workshopId={}", workshopId, e);
            return R.fail("查询车间详情失败: " + e.getMessage());
        }
    }

    @Override
    public R<List<WorkshopViewEntity>> getByFactoryId(Long factoryId) {
        try {
            List<WorkshopViewEntity> workshops = workshopViewService.getByFactoryId(factoryId);
            return R.ok(workshops, "查询成功");
        } catch (Exception e) {
            log.error("根据工厂ID查询车间列表失败, factoryId={}", factoryId, e);
            return R.fail("根据工厂ID查询车间列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<Page<WorkshopViewEntity>> getByStatus(Page<WorkshopViewEntity> page, String status) {
        try {
            LambdaQueryWrapper<WorkshopViewEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WorkshopViewEntity::getStatus, status);
            queryWrapper.orderByDesc(WorkshopViewEntity::getCreatedTime);
            
            Page<WorkshopViewEntity> result = workshopViewService.page(page, queryWrapper);
            return R.ok(result, "查询成功");
            
        } catch (Exception e) {
            log.error("根据状态查询车间列表失败, status={}", status, e);
            return R.fail("根据状态查询车间列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<List<WorkshopViewEntity>> getEnabledByFactoryId(Long factoryId) {
        try {
            log.info("开始查询工厂下启用状态的车间列表: factoryId={}", factoryId);
            
            // 检查工厂是否存在
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory == null) {
                return R.fail("所属工厂不存在");
            }
            
            LambdaQueryWrapper<WorkshopViewEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WorkshopViewEntity::getFactoryId, factoryId);
            queryWrapper.eq(WorkshopViewEntity::getStatus, "enable");
            queryWrapper.orderByAsc(WorkshopViewEntity::getId);
            
            List<WorkshopViewEntity> workshops = workshopViewService.list(queryWrapper);
            
            log.info("查询工厂下启用状态的车间列表成功: factoryId={}, count={}", factoryId, workshops.size());
            return R.ok(workshops, "查询成功");
            
        } catch (Exception e) {
            log.error("根据工厂ID查询启用状态的车间列表失败, factoryId={}", factoryId, e);
            return R.fail("根据工厂ID查询启用状态的车间列表失败: " + e.getMessage());
        }
    }
}